;/******************************************************************************
;/* @file   start.s
;/* @brief  start code for ARM9
;/* @date   2025-01-13
;/* @author kerndev@foxmail.com
;/*****************************************************************************/
Stack_Size       EQU     0x00000400
Heap_Size        EQU     0x00000000

	AREA STACK, NOINIT, READWRITE, ALIGN=3
Stack_Mem        SPACE   Stack_Size

	AREA HEAP, NOINIT, READWRITE, ALIGN=3
Heap_Mem         SPACE   Heap_Size

;/*****************************************************************************/
; User Initial Stack & Heap
	AREA |.text|, CODE, READONLY
	EXPORT  __user_initial_stackheap
__user_initial_stackheap PROC
	LDR     R0, = Heap_Mem
	LDR     R1, = (Stack_Mem + Stack_Size)
	LDR     R2, = (Heap_Mem +  Heap_Size)
	LDR     R3, = Stack_Mem
	BX      LR
	ENDP

;/*****************************************************************************/
; Vector_Table
	AREA RESET, CODE, READONLY
	IMPORT IRQ_Handler
	IMPORT SWI_Handler
	EXPORT Reset_Handler
Vector_Table
	LDR     PC, Reset_Addr
	LDR     PC, Undefined_Addr
	LDR     PC, SWI_Addr
	LDR     PC, Prefetch_Addr
	LDR     PC, Abort_Addr
	LDR     PC, Reserved_Addr
	LDR     PC, IRQ_Addr
	LDR     PC, FIQ_Addr

Reset_Addr       DCD    Reset_Handler
Undefined_Addr   DCD    Reset_Handler
SWI_Addr         DCD    SWI_Handler
Prefetch_Addr    DCD    Reset_Handler
Abort_Addr       DCD    Reset_Handler
Reserved_Addr    DCD    Reset_Handler
IRQ_Addr         DCD    IRQ_Handler
FIQ_Addr         DCD    Reset_Handler

;/*****************************************************************************/
; Mode bits and interrupt flag (I&F) defines
IRQ_MODE_NO_INT  EQU    0xD2
SVC_MODE_NO_INT  EQU    0xD3
SYS_MODE_NO_INT  EQU    0xDF

;/*****************************************************************************/
; Reset Handler
Reset_Handler PROC
	IMPORT  __main

	MSR     CPSR_c, #SYS_MODE_NO_INT
	LDR     SP, =(Stack_Mem + Stack_Size)
	
	;Setup Vector Table
	MRC     p15, 0, R2, c1, c0, 0  ;Read CP15 to R2
	ANDS    R2, R2, #(1 << 13)
	LDREQ   R1, =0x00000000
	LDRNE   R1, =0xFFFF0000
	LDR     R0, =Vector_Table
	LDMIA   R0!, {R2-R9}
	STMIA   R1!, {R2-R9}
	LDMIA   R0!, {R2-R9}
	STMIA   R1!, {R2-R9}
	LDR     R0, =__main
	BX      R0
	ENDP
	
	END
